<template>
  <div style="display: flex; justify-content: center; align-items: center">
    <div
      style="
        min-width: 900px;
        width: 900px;
        background-color: #fff;
        margin-top: 20px;
        padding: 20px;
        height: calc(100vh - 140px);
        overflow-y: auto;
      "
    >
      <div id="printBox1" ref="pdfContent" v-loading="loading">
        <!-- 循环生成第几页 page-break为打印分页标识-->
        <!-- <div
          v-for="(pageItem, pageIndex) in printDataList"
          :key="pageItem?.id"
          class="page-break"
        > -->

        <div style="position: relative" ref="tableAll" id="table1">
          <div style="position: relative; height: 76px">
            <img
              src="@/assets/images/screen/jtlogo_sm.png"
              width="170"
              style="position: absolute; left: 0px; top: 5px"
            />
            <div
              style="font-size: 20px; display: flex; justify-content: center"
            >
              <div class="box1">
                <!-- <span>Dalian Giantech Automobile Parts Co., Ltd.</span> -->
                <span style="font-size: 20px">材质检验报告</span>
                <span style="font-size: 20px">Material Inspection Report</span>
              </div>
            </div>

            <!-- 送货单基本信息 -->
            <div
              style="
                display: flex;
                margin-bottom: 2px;
                font-size: 15px;
                font-weight: 400;
                color: #6e7073;
                margin-top: -7px;
              "
            >
              <div style="flex: 1"></div>
              <div style="flex: 1">
                <div style="text-align: right">
                  NO:{{ formData?.reportCode || "" }}
                </div>
              </div>
            </div>
          </div>
          <table
            border="1"
            cellpadding="0"
            cellspacing="0"
            align="center"
            class="dashed-border"
          >
            <colgroup>
              <col width="60" />
              <col width="60" />
              <col width="60" />
              <col width="60" />
              <col width="60" />
              <col width="60" />

              <col width="60" />
              <col width="60" />
              <col width="60" />
              <col width="60" />
              <col width="60" />
              <col width="60" />
            </colgroup>
            <tbody>
              <tr class="tr_1">
                <td colspan="2">
                  <div class="box1">
                    <div>供应商</div>
                    <div>Supplier</div>
                  </div>
                </td>
                <td colspan="10">
                  <div class="box1">
                    <div style="font-size: 15px">
                      大连金泰汽车零部件有限公司
                    </div>
                    <div>Dalian Giantech Automobile Parts Company</div>
                  </div>
                </td>
              </tr>
              <tr class="tr_2">
                <td colspan="2">
                  <div class="box1">
                    <div>客户</div>
                    <div>Customer</div>
                  </div>
                </td>
                <td colspan="2">
                  {{ formData?.customerName || "" }}
                </td>
                <td colspan="2">
                  <div class="box1">
                    <div>品名</div>
                    <div>Part Name</div>
                  </div>
                </td>
                <td colspan="2">
                  {{ formData?.materialName || "" }}
                </td>
                <td colspan="2">
                  <div class="box1">
                    <div>品号</div>
                    <div>Part NO.</div>
                  </div>
                </td>
                <td colspan="2">
                  {{ formData?.materialCode || "" }}
                </td>
              </tr>

              <tr class="tr_3">
                <td colspan="2">
                  <div class="box1">
                    <div>批号</div>
                    <div>Lot/Batch</div>
                  </div>
                </td>
                <td colspan="2">
                  {{ formData?.materialBatch || "" }}
                </td>
                <td colspan="2">
                  <div class="box1">
                    <div>材质</div>
                    <div>Material</div>
                  </div>
                </td>
                <td colspan="2">
                  {{ formData?.materialQuality || "" }}
                </td>
                <td colspan="2">
                  <div class="box1">
                    <div>生产日期</div>
                    <div>Production Date</div>
                  </div>
                </td>
                <td colspan="2">
                  {{ formData?.approveDate || "" }}
                </td>
              </tr>
              <tr style="line-height: 0" class="tr_4">
                <td colspan="12" style="line-height: 0">
                  <div
                    style="min-height: 180px; max-height: 300px; line-height: 0"
                  >
                    <img
                      v-if="formData.image && formData.image.length > 0"
                      :src="`${upPreviewUrl}/${formData.image[0].url}`"
                      width="100%"
                      style="max-height: 300px"
                    />
                  </div>
                </td>
              </tr>
              <tr class="tr_5">
                <td colspan="1">
                  <div class="box1">
                    <div>编号</div>
                    <div>NO.</div>
                  </div>
                </td>
                <td colspan="3">
                  <div class="box1">
                    <div>检验项目</div>
                    <div>Test Item</div>
                  </div>
                </td>
                <td colspan="1">
                  <div class="box1">
                    <div>规格</div>
                    <div>Spec.</div>
                  </div>
                </td>
                <td colspan="3">
                  <div class="box1">
                    <div>方法</div>
                    <div>Method</div>
                  </div>
                </td>
                <td colspan="3">
                  <div class="box1">
                    <div>检验结果</div>
                    <div>Test Result(s)</div>
                  </div>
                </td>
                <td colspan="1" style="padding: 0">
                  <div class="box1">
                    <div>判定</div>
                    <div style="font-size: 10px">Judgement</div>
                  </div>
                </td>
              </tr>

              <template
                v-for="(group, groupName) in groupedData"
                :key="groupName"
              >
                <tr
                  v-for="(row, rowIndex) in group?.rows"
                  :key="rowIndex"
                  class="tr_item"
                >
                  <td>{{ row?.dataIndex || "" }}</td>
                  <td
                    :rowspan="group.rowspan"
                    v-if="rowIndex === 0"
                    colspan="3"
                  >
                    {{ row?.sopItemName || "" }}
                  </td>
                  <!-- <td>{{ row.sopItemStandard }}</td> -->
                  <td></td>
                  <td
                    colspan="3"
                    :rowspan="group.rowspan"
                    v-if="rowIndex === 0"
                  >
                    {{ row?.sopItemMethod || "" }}
                  </td>
                  <td
                    v-if="
                      row.sopItemPosition !== null && row.sopItemPosition !== ''
                    "
                    colspan="2"
                  >
                    <div>
                      {{ row.sopItemPosition || "" }}
                    </div>
                  </td>
                  <td :colspan="row.sopItemPosition ? 1 : 3">
                    <div>
                      {{ row.sopItemValue || "" }}
                    </div>
                  </td>
                  <td colspan="1">
                    <div>
                      {{
                        row.sopItemResult === "1"
                          ? "OK"
                          : row.sopItemResult === "0"
                          ? "NO"
                          : ""
                      }}
                    </div>
                  </td>
                </tr>
              </template>

              <tr v-if="groupedData.length === 0" class="tr_item">
                <td colspan="12" style="height: 90px"></td>
              </tr>
              <tr class="tr_7">
                <td colspan="12">
                  <div>
                    <span>金相图片metallograph</span>
                    <span style="margin-left: 15px">×100</span>
                    <span style="margin-left: 60px">硝酸浓度EtchedNital</span>
                    <span style="margin-left: 15px">5%</span>
                  </div>
                </td>
              </tr>

              <tr
                v-if="imageRows.length === 0"
                style="height: 110px; line-height: 0"
                class="tr_image"
              >
                <td colspan="12" style="height: 110px; line-height: 0"></td>
              </tr>
              <template v-else>
                <tr
                  v-for="(row, rowIndex) in imageRows"
                  :key="rowIndex"
                  style="height: 110px; line-height: 0"
                  class="tr_image"
                >
                  <td
                    v-for="(img, colIndex) in row"
                    :key="colIndex"
                    colspan="4"
                    style="line-height: 0"
                  >
                    <img
                      v-if="img.url"
                      :src="`${upPreviewUrl}${img.url}`"
                      style="
                        width: auto;
                        max-width: 250px;
                        height: 100px;
                        margin: 0px;
                        cursor: pointer;
                      "
                      @click="
                        handlePictureCardPreview(`${upPreviewUrl}${img.url}`)
                      "
                      alt=""
                    />
                  </td>
                </tr>
              </template>

              <tr class="tr_8">
                <td colspan="3">
                  <div class="box1">
                    <div>综合判定</div>
                    <div>ComprehensiveJudgement</div>
                  </div>
                </td>
                <td colspan="9">
                  {{
                    formData?.comprehensiveJudgment === "0"
                      ? "No"
                      : formData?.comprehensiveJudgment === "1"
                      ? "OK"
                      : ""
                  }}
                </td>
              </tr>
              <tr>
                <td colspan="3">
                  <div class="box1">
                    <div>检验人</div>
                    <div>Inspector</div>
                  </div>
                </td>
                <td colspan="3">
                  {{ formData?.inspector || "" }}
                </td>
                <td colspan="3">
                  <div class="box1">
                    <div>核准人</div>
                    <div>QC</div>
                  </div>
                </td>
                <td colspan="3">
                  {{ formData?.approveUserName || "" }}
                </td>
              </tr>
              <tr>
                <td colspan="3">
                  <div class="box1">
                    <div>检验日期</div>
                    <div>Date</div>
                  </div>
                </td>
                <td colspan="3">
                  {{ formData?.inspectDate || "" }}
                </td>
                <td colspan="3">
                  <div class="box1">
                    <div>核准日期</div>
                    <div>Date</div>
                  </div>
                </td>
                <td colspan="3">
                  {{ formData?.approveDate || "" }}
                </td>
              </tr>
            </tbody>
          </table>

          <!-- 信息提示区域 -->
        </div>
        <!-- </div> -->
      </div>

      <div id="printBox" ref="pdfContent" v-show="startPdf">
        <!-- 循环生成第几页 page-break为打印分页标识-->
        <div
          v-for="(pageItem, pageIndex) in groupList"
          :key="pageIndex"
          :class="pageIndex === 0 ? '0' : 'page-break'"
          style="height: 1070px; position: relative; width: 750px"
        >
          <!-- <el-divider border-style="dashed" style="margin: 20px 0" /> -->
          <div style="position: relative" ref="tableAll" id="table1">
            <div style="position: relative; height: 76px">
              <img
                src="@/assets/images/screen/jtlogo_sm.png"
                width="170"
                style="position: absolute; left: 0px; top: 5px"
              />
              <div
                style="font-size: 20px; display: flex; justify-content: center"
              >
                <div class="box1">
                  <!-- <span>Dalian Giantech Automobile Parts Co., Ltd.</span> -->
                  <span style="font-size: 20px">材质检验报告</span>
                  <span style="font-size: 20px"
                    >Material Inspection Report</span
                  >
                </div>
              </div>

              <!-- 送货单基本信息 -->
              <div
                style="
                  display: flex;
                  margin-bottom: 2px;
                  font-size: 15px;
                  font-weight: 400;
                  color: #6e7073;
                  margin-top: -7px;
                "
              >
                <div style="flex: 1"></div>
                <div style="flex: 1">
                  <div style="text-align: right">
                    NO:{{ formData?.reportCode || "" }}
                  </div>
                </div>
              </div>
            </div>
            <table
              border="1"
              cellpadding="0"
              cellspacing="0"
              align="center"
              class="dashed-border"
              style="width: 100%"
            >
              <colgroup>
                <col width="60" />
                <col width="60" />
                <col width="60" />
                <col width="60" />
                <col width="60" />
                <col width="60" />

                <col width="60" />
                <col width="60" />
                <col width="60" />
                <col width="60" />
                <col width="60" />
                <col width="60" />
              </colgroup>
              <tbody>
                <template v-if="pageIndex === 0">
                  <tr class="tr_1">
                    <td colspan="2">
                      <div class="box1">
                        <div>供应商</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Supplier
                        </div>
                      </div>
                    </td>
                    <td colspan="10">
                      <div class="box1">
                        <div style="font-size: 15px">
                          大连金泰汽车零部件有限公司
                        </div>
                        <div style="font-size: 13px; line-height: 20px">
                          Dalian Giantech Automobile Parts Company
                        </div>
                      </div>
                    </td>
                  </tr>
                  <tr class="tr_2">
                    <td colspan="2">
                      <div class="box1">
                        <div>客户</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Customer
                        </div>
                      </div>
                    </td>
                    <td colspan="2">
                      {{ formData?.customerName || "" }}
                    </td>
                    <td colspan="2">
                      <div class="box1">
                        <div>品名</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Part Name
                        </div>
                      </div>
                    </td>
                    <td colspan="2">
                      {{ formData?.materialName || "" }}
                    </td>
                    <td colspan="2">
                      <div class="box1">
                        <div>品号</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Part NO.
                        </div>
                      </div>
                    </td>
                    <td colspan="2">
                      {{ formData?.materialCode || "" }}
                    </td>
                  </tr>

                  <tr class="tr_3">
                    <td colspan="2">
                      <div class="box1">
                        <div>批号</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Lot/Batch
                        </div>
                      </div>
                    </td>
                    <td colspan="2">
                      {{ formData?.materialBatch || "" }}
                    </td>
                    <td colspan="2">
                      <div class="box1">
                        <div>材质</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Material
                        </div>
                      </div>
                    </td>
                    <td colspan="2" style="font-size: 13px; line-height: 16px">
                      {{ formData?.materialQuality || "" }}
                    </td>
                    <td colspan="2">
                      <div class="box1">
                        <div>生产日期</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Production Date
                        </div>
                      </div>
                    </td>
                    <td colspan="2" style="font-size: 12px">
                      {{ formData?.approveDate || "" }}
                    </td>
                  </tr>
                  <!-- <tr style="line-height: 0" class="tr_4">
                    <td colspan="12" style="line-height: 0">
                      <div
                        style="
                          min-height: 180px;
                          max-height: 300px;
                          line-height: 0;
                        "
                      ></div>
                    </td>
                  </tr> -->
                  <tr style="line-height: 0" class="tr_4">
                    <td colspan="12" style="line-height: 0">
                      <div
                        style="
                          min-height: 180px;
                          max-height: 300px;
                          line-height: 0;
                        "
                      >
                        <img
                          v-if="formData.image && formData.image.length > 0"
                          :src="`${upPreviewUrl}/${formData.image[0].url}`"
                          width="100%"
                          style="max-height: 300px"
                        />
                      </div>
                    </td>
                  </tr>
                  <tr class="tr_5">
                    <td colspan="1">
                      <div class="box1">
                        <div>编号</div>
                        <div style="font-size: 13px; line-height: 20px">
                          NO.
                        </div>
                      </div>
                    </td>
                    <td colspan="3">
                      <div class="box1">
                        <div>检验项目</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Test Item
                        </div>
                      </div>
                    </td>
                    <td colspan="1">
                      <div class="box1">
                        <div>规格</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Spec.
                        </div>
                      </div>
                    </td>
                    <td colspan="3">
                      <div class="box1">
                        <div>方法</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Method
                        </div>
                      </div>
                    </td>
                    <td colspan="3">
                      <div class="box1">
                        <div>检验结果</div>
                        <div style="font-size: 13px; line-height: 20px">
                          Test Result(s)
                        </div>
                      </div>
                    </td>
                    <td colspan="1" style="padding: 0">
                      <div class="box1">
                        <div>判定</div>
                        <div style="font-size: 10px">Judgement</div>
                      </div>
                    </td>
                  </tr>
                </template>

                <template
                  v-for="(group, groupName) in pageItem?.itemListTable"
                  :key="groupName"
                >
                  <tr
                    v-for="(row, rowIndex) in group.rows"
                    :key="rowIndex"
                    class="tr_item_1"
                  >
                    <td>{{ row?.dataIndex || "" }}</td>
                    <td
                      :rowspan="group.rowspan"
                      v-if="rowIndex === 0"
                      colspan="3"
                    >
                      {{ row?.sopItemName || "" }}
                    </td>
                    <!-- <td>{{ row.sopItemStandard }}</td> -->
                    <td></td>
                    <td
                      colspan="3"
                      :rowspan="group.rowspan"
                      v-if="rowIndex === 0"
                      style="font-size: 13px; line-height: 18px"
                    >
                      {{ row?.sopItemMethod || "" }}
                    </td>
                    <td
                      v-if="
                        row.sopItemPosition !== null &&
                        row.sopItemPosition !== ''
                      "
                      colspan="2"
                    >
                      <div>
                        {{ row.sopItemPosition || "" }}
                      </div>
                    </td>
                    <td :colspan="row.sopItemPosition ? 1 : 3">
                      <div>
                        {{ row.sopItemValue || "" }}
                      </div>
                    </td>
                    <td colspan="1">
                      <div>
                        {{
                          row.sopItemResult === "1"
                            ? "OK"
                            : row.sopItemResult === "0"
                            ? "NO"
                            : ""
                        }}
                      </div>
                    </td>
                  </tr>
                </template>

                <tr v-if="pageItem.noItem" class="tr_item_1">
                  <td colspan="12" style="height: 90px"></td>
                </tr>

                <tr class="tr_7" v-if="pageItem.showImageTitle">
                  <td colspan="12">
                    <div>
                      <span>金相图片metallograph</span>
                      <span style="margin-left: 15px">×100</span>
                      <span style="margin-left: 60px">硝酸浓度EtchedNital</span>
                      <span style="margin-left: 15px">5%</span>
                    </div>
                  </td>
                </tr>

                <tr v-if="pageItem.noImage" class="tr_item_1">
                  <td colspan="12" style="height: 90px"></td>
                </tr>
                <!-- (group, groupName) in pageItem.itemListTable -->
                <!-- <tr
                  v-if="pageItem.imageListTable.length === 0"
                  style="height: 110px; line-height: 0"
                  class=""
                >
                  <td colspan="12" style="height: 110px; line-height: 0"></td>
                </tr> -->
                <template v-if="pageItem.imageListTable.length !== 0">
                  <tr
                    v-for="(row, rowIndex) in pageItem?.imageListTable"
                    :key="rowIndex"
                    style="height: 110px; line-height: 0"
                    class=""
                  >
                    <td
                      v-for="(img, colIndex) in row"
                      :key="colIndex"
                      colspan="4"
                      style="line-height: 0"
                    >
                      <img
                        v-if="img.url"
                        :src="`${upPreviewUrl}${img.url}`"
                        style="
                          width: auto;
                          max-width: 250px;
                          height: 100px;
                          margin: 0px;
                          cursor: pointer;
                        "
                        @click="
                          handlePictureCardPreview(`${upPreviewUrl}${img.url}`)
                        "
                        alt=""
                      />
                    </td>
                  </tr>
                </template>

                <tr v-if="pageItem.showSummary1">
                  <td colspan="3">
                    <div class="box1">
                      <div>综合判定</div>
                      <div style="font-size: 13px; line-height: 20px">
                        ComprehensiveJudgement
                      </div>
                    </div>
                  </td>
                  <td colspan="9">
                    {{
                      formData?.comprehensiveJudgment === "0"
                        ? "No"
                        : formData?.comprehensiveJudgment === "1"
                        ? "OK"
                        : ""
                    }}
                  </td>
                </tr>
                <tr v-if="pageItem.showSummary2">
                  <td colspan="3">
                    <div class="box1">
                      <div>检验人</div>
                      <div style="font-size: 13px; line-height: 20px">
                        Inspector
                      </div>
                    </div>
                  </td>
                  <td colspan="3">
                    {{ formData?.inspector || "" }}
                  </td>
                  <td colspan="3">
                    <div class="box1">
                      <div>核准人</div>
                      <div style="font-size: 13px; line-height: 20px">QC</div>
                    </div>
                  </td>
                  <td colspan="3">
                    {{ formData?.approveUserName || "" }}
                  </td>
                </tr>
                <tr v-if="pageItem.showSummary3">
                  <td colspan="3">
                    <div class="box1">
                      <div>检验日期</div>
                      <div style="font-size: 13px; line-height: 20px">Date</div>
                    </div>
                  </td>
                  <td colspan="3">
                    {{ formData?.inspectDate || "" }}
                  </td>
                  <td colspan="3">
                    <div class="box1">
                      <div>核准日期</div>
                      <div style="font-size: 13px; line-height: 20px">Date</div>
                    </div>
                  </td>
                  <td colspan="3">
                    {{ formData?.approveDate || "" }}
                  </td>
                </tr>
              </tbody>
            </table>

            <!-- 信息提示区域 -->
          </div>

          <div
            style="
              position: absolute;
              width: 100%;
              text-align: center;
              bottom: 0;
              left: 0;
              font-size: 12px;
            "
          >
            当前页：{{ pageIndex + 1 }}，总计：{{ groupList.length }}
          </div>
        </div>
      </div>
    </div>

    <div class="flex flex-col ml-3">
      <div>
        <el-button type="primary" @click="startPrint" class="mb-2 w-[96px]"
          >打 印</el-button
        >
      </div>

      <div>
        <el-button type="primary" @click="downloadPDF" class="mb-2 w-[96px]"
          >下载 PDF</el-button
        >
      </div>

      <div>
        <el-button @click="previewPDF" class="mb-2 w-[96px]"
          >预览 PDF</el-button
        >
      </div>
    </div>

    <el-dialog
      v-model="pdfPreviewDialog"
      title="PDF 预览"
      width="1100"
      :close-on-click-modal="false"
      draggable
      alignCenter
      class="printDialog"
    >
      <div style="height: 650px">
        <div v-if="pdfPreviewUrl" style="height: 650px">
          <embed
            :src="pdfPreviewUrl"
            type="application/pdf"
            style="width: 100%; height: 100%"
          />
        </div>
        <div v-else>正在生成预览，请稍候...</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import html2pdfs from "html2pdf.js";
import printJS from "print-js";
import { mock } from "./index";
import { useRoute } from "vue-router";
import { useReportModelConfigStore } from "@/views/qms/pinia/ReportModelConfigStore";

const route = useRoute();

defineOptions({
  name: "QMSMATERIALINSPECTIONREPORT",
  inheritAttrs: false,
});

const loading = ref(false);

// 处理数据，计算 rowspan 和隐藏标志
// 计算分组后的数据
const groupedData = computed(() => {
  const result: any = {};
  const dataReal = JSON.parse(
    JSON.stringify(formData.value?.checkOrderDetails || [])
  );
  let dataRealIndex = 0;
  dataReal.forEach((item: any) => {
    if (!result[item.sopItemName]) {
      result[item.sopItemName] = {
        rowspan: 0,
        rows: [],
      };
    }
    dataRealIndex += 1;
    result[item.sopItemName].rows.push({
      dataRealIndex: dataRealIndex,
      sopItemName: item.sopItemName,
      sopItemStandard: item.sopItemStandard,
      sopItemMethod: item.sopItemMethod,
      sopItemPosition: item.sopItemPosition,
      sopItemValue: item.sopItemValue,
      sopItemResult: item.sopItemResult,
    });
    result[item.sopItemName].rowspan++;
  });

  // 转换为有序的对象数组
  const colRes = Object.entries(result).map(([name, info]) => ({
    name,
    ...info,
  }));

  let realIndex = 0;
  colRes?.forEach((resItem) => {
    resItem.rows?.forEach((rows: any) => {
      realIndex += 1;
      rows.dataIndex = realIndex;
    });
  });
  return colRes;
});

function filterTable(list) {
  const elderlist = list;

  let index1 = 0;

  for (let i = 0; i < elderlist.length; i++) {
    const item = elderlist[i];
    const result: any = {};

    // 处理数据，计算 rowspan 和隐藏标志
    // 计算分组后的数据

    const dataReal = JSON.parse(JSON.stringify(item?.itemList || []));
    let dataRealIndex = 0;
    if (dataReal && dataReal.length > 0) {
      dataReal.forEach((item: any) => {
        if (!result[item?.sopItemName]) {
          result[item?.sopItemName] = {
            rowspan: 0,
            rows: [],
          };
        }
        dataRealIndex += 1;
        result[item?.sopItemName].rows.push({
          dataRealIndex: dataRealIndex,
          sopItemName: item.sopItemName,
          sopItemStandard: item.sopItemStandard,
          sopItemMethod: item.sopItemMethod,
          sopItemPosition: item.sopItemPosition,
          sopItemValue: item.sopItemValue,
          sopItemResult: item.sopItemResult,
        });
        result[item?.sopItemName].rowspan++;
      });
    }

    // 转换为有序的对象数组
    const colRes = Object.entries(result).map(([name, info]) => ({
      name,
      ...info,
    }));

    colRes?.forEach((resItem) => {
      // realIndex += resItem.rowspan;
      resItem.rows?.forEach((rows: any) => {
        index1 += 1;
        rows.dataIndex = index1;
      });
    });
    elderlist[i].itemListTable = colRes;

    // 图片处理 三个一行
    let rows = [];
    const dataImage = JSON.parse(JSON.stringify(item?.imageList || []));
    if (dataImage && dataImage.length > 0) {
      for (let i = 0; i < dataImage.length; i += 3) {
        rows.push(dataImage.slice(i, i + 3));
      }
    }
    elderlist[i].imageListTable = rows;
  }
  return elderlist;
}

// 图片预览功能
const uploadApi = import.meta.env.VITE_APP_BASE_API;
const upPreviewUrl = `${uploadApi}/system/fileCenter/preview/`;
const handlePictureCardPreview = (url: string) => {
  url = url?.replace("fileCenter/download/", "fileCenter/preview/");
  window.open(url);
};

// onMounted(() => {
//   if (route.query.id) {
//     getDetail();
//   } else {
//     formData.value = {};
//     setTimeout(() => {
//       computedHeight();
//     }, 200);
//   }
// });

onActivated(() => {
  groupList_1.value = [
    {
      page: 1,
      itemList: [],
      itemListTable: [],
      showImageTitle: false,
    },
  ];

  groupList.value = [
    {
      page: 1,
      itemList: [],
      itemListTable: [],
      showImageTitle: false,
    },
  ];

  if (route.query.id) {
    getDetail();
  } else {
    formData.value = {};
  }
  fillData();
});

const fillData = async () => {
  const reportStore = useReportModelConfigStore();

  const previewData = reportStore.previewData;
  if (previewData) {
    console.log("从store接收到的formData:", previewData);

    formData.value.image = previewData.images;
    console.log("formData.image", formData.value.image);
    formData.value.customerName = previewData.customerName;
    formData.value.materialDrawingNo = previewData.materialDrawingNo;
    formData.value.materialName = previewData.materialName;
    formData.value.materialCode = previewData.materialCode;
    if (previewData.details && previewData.details.length > 0) {
      const checkItemIds = previewData.details.map((item) => item.checkItemId);
      Promise.all(
        checkItemIds.flatMap(async (item) => {
          const { data } = await getCheckItem(item);
          return data;
        })
      )
        .then((data) => {
          formData.value.checkOrderDetails = data.flat();
        })
        .finally(() => {
          setTimeout(() => {
            computedHeight();
          }, 500);
        });
    }
    // reportStore.clearPreviewData();
  } else {
    Object.assign(formData.value, {});
    setTimeout(() => {
      computedHeight();
    }, 500);
  }
};

const getCheckItem = async (checkItemId: any[] = []) => {
  return await request({
    url: `/qms/qmssopitem/getListByCheckItemId`,
    method: "post",
    data: { checkItemId },
  });
};
// 打印数据
const getDetail = async () => {
  loading.value = true;
  await request({
    url: `/qms/qmsreportrecord/report/query`,
    method: "get",
    params: {
      reportRecordId: route.query.id,
    },
  })
    .then((res) => {
      if (res.data != null) {
        formData.value = res.data;
        loading.value = false;
      } else {
        loading.value = false;
      }
      setTimeout(() => {
        computedHeight();
      }, 200);
    })
    .finally(() => {
      loading.value = false;
    });
};

const startPdf = ref(false);

// 开始打印
function startPrint() {
  startPdf.value = true;
  // 开始打印
  setTimeout(() => {
    printJS({
      printable: "printBox", // 打印内容的容器 id
      type: "html", // 打印类型
      imageStyle: "",
      scanStyles: false,
      style: `
      @media print {
        @page {
          margin: 7mm 5mm;
        }
        body {
          margin: 0;
        }
        div,
        table,
        tr,
        td,
        th,
        tbody,
        thead,
        span,
        image {
          padding: 0;
          margin: 0;
        }
        .page-break {
          page-break-before: always;
        }
        .dashed-border {
          width: 100%;
          border-collapse: collapse; /* 使边框合并为单一边框 */
          border: 1px solid #333;
        }

        .dashed-border td,
        .dashed-border th {
          font-size: 13px;
          border: 1px solid #333;
          min-height: 30px;
          padding: 4px 6px;
          overflow-wrap: anywhere;
          line-height: 20px;
          word-break: break-all;
        }

        tr {
          page-break-inside: avoid;
        }

        .bold td {
          font-weight: 600;
          text-align: center;
        }

        td {
          text-align: center;
        }

        .left td {
          text-align: left;
        }

        .box1 {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }

        .box1 div:nth-child(1) {
          font-size: 14px;
        }
        .box1 div:nth-child(2) {
          line-height: 20px;
          font-size: 13px;
        }
      }
    `,
    });

    startPdf.value = false;
  }, 500);
}

// 模拟数据
// const formData = ref(mock.data);
const formData = ref<any>({});

const pdfContent = ref(null);
const pdfPreviewDialog = ref(false);
const pdfPreviewUrl = ref<any>(null);

const pdfOptions = {
  filename: formData.value?.reportCode
    ? `材质检验报告(${formData.value?.reportCode})`
    : `材质检验报告.pdf`, // 指定生成文件的名称
  margin: [6, 5],
  image: { type: "jpeg", quality: 2 },
  html2canvas: { scale: 2, useCORS: true, logging: false },
  jsPDF: { unit: "mm", format: "a4", orientation: "portrait" },
  splitTextToRows: false, // 关闭文本拆分行
};
const previewPDF = () => {
  startPdf.value = true;

  const element = pdfContent.value;

  if (!element) {
    console.error("Error: pdfContent is not defined or not bound to the DOM.");
    return;
  }

  const container = document.getElementById("printBox");
  if (!container) {
    console.error("Error: #pdf-content element not found in the DOM.");
    return;
  }

  container.classList.add("export");

  pdfPreviewDialog.value = true;
  pdfPreviewUrl.value = null;

  html2pdfs()
    .from(element)
    .set(pdfOptions)
    .toPdf()
    .get("pdf")
    .then((pdf: any) => {
      const pdfBlob = pdf.output("blob");
      pdfPreviewUrl.value = URL.createObjectURL(pdfBlob);
    })
    .finally(() => {
      container.classList.remove("export");
      startPdf.value = false;
    });
};

const downloadPDF = () => {
  startPdf.value = true;
  const element = pdfContent.value;
  html2pdfs()
    .set(pdfOptions)
    .from(element)
    .save()
    .finally(() => {
      startPdf.value = false;
    });
};

// 每3个分一组
const imageRows = computed(() => {
  let rows = [];
  if (formData.value?.images && formData.value?.images.length > 0) {
    for (let i = 0; i < formData.value?.images.length; i += 3) {
      rows.push(formData.value?.images.slice(i, i + 3));
    }
  }
  return rows;
});

const groupList_1 = ref<any>([
  {
    page: 1,
    itemList: [],
    imageList: [],
    imageListTable: [],
    itemListTable: [],
    showImageTitle: false,
  },
]);

const groupList = ref<any>([
  {
    page: 1,
    itemList: [], // 检验项
    imageList: [], // 图片
    imageListTable: [],
    itemListTable: [],
    showImageTitle: false, // 图片头部
  },
]);
function computedHeight() {
  let totalHeight = 0;
  const headerHeight = 76;
  const tr1Height =
    document.getElementsByClassName("tr_1")?.[0]?.clientHeight ?? 0;
  const tr2Height =
    document.getElementsByClassName("tr_2")?.[0]?.clientHeight ?? 0;
  const tr3Height =
    document.getElementsByClassName("tr_3")?.[0]?.clientHeight ?? 0;
  const tr4Height =
    document.getElementsByClassName("tr_4")?.[0]?.clientHeight ?? 0;
  const tr5Height =
    document.getElementsByClassName("tr_5")?.[0]?.clientHeight ?? 0;

  // 第一页头部高度
  totalHeight =
    headerHeight + tr1Height + tr2Height + tr3Height + tr4Height + tr5Height;

  // 判断检验项是否分页
  if (
    formData.value?.checkOrderDetails &&
    formData.value?.checkOrderDetails.length > 0
  ) {
    const itemList = document.getElementsByClassName("tr_item");
    for (let i = 0; i < itemList?.length; i++) {
      const item = itemList[i];
      totalHeight += item.clientHeight;
      if (totalHeight < 1050) {
        groupList_1.value[groupList_1.value.length - 1].itemList.push(
          formData.value?.checkOrderDetails[i]
        );
      } else {
        groupList_1.value.push({
          page: groupList_1.value[groupList_1.value.length - 1].page + 1,
          itemList: [formData.value?.checkOrderDetails[i]],
          imageList: [],
          imageListTable: [],
          itemListTable: [],
          showImageTitle: false,
        });
        totalHeight = headerHeight + item.clientHeight;
      }
    }
  } else {
    // noItem
    if (totalHeight + 90 < 1050) {
      groupList_1.value[groupList_1.value.length - 1].noItem = true;
      totalHeight += 90;
    } else {
      groupList_1.value.push({
        page: groupList_1.value[groupList_1.value.length - 1].page + 1,
        itemList: [],
        imageList: [],
        imageListTable: [],
        itemListTable: [],
        showImageTitle: false,
        noItem: true,
      });
      totalHeight = headerHeight + 90;
    }
  }

  // 判断图片头部展示位置，如果当页能放下头部，则直接添加；放不下则分页展示
  if (totalHeight < 1050 - 29) {
    groupList_1.value[groupList_1.value.length - 1].showImageTitle = true;
    totalHeight += 29;
  } else {
    groupList_1.value.push({
      page: groupList_1.value[groupList_1.value.length - 1].page + 1,
      itemList: [],
      imageList: [],
      imageListTable: [],
      itemListTable: [],
      showImageTitle: true,
    });
    totalHeight = headerHeight + 29;
  }

  // 判断图片是否分页
  if (formData.value?.images && formData.value?.images.length > 0) {
    const imageList = document.getElementsByClassName("tr_image");
    for (let i = 0; i < imageList?.length; i++) {
      const item = imageList[i];
      totalHeight += item.clientHeight;
      if (totalHeight < 1050) {
        for (let j = 0; j < 3; j++) {
          groupList_1.value[groupList_1.value.length - 1].imageList.push(
            formData.value?.images[i * 3 + j] ?? {}
          );
        }
      } else {
        let list2 = [];
        for (let j = 0; j < 3; j++) {
          list2.push(formData.value?.images[i * 3 + j] ?? {});
        }

        groupList_1.value.push({
          page: groupList_1.value[groupList_1.value.length - 1].page + 1,
          itemList: [],
          imageList: list2,
          imageListTable: [],
          itemListTable: [],
          showImageTitle: false,
        });
        totalHeight = headerHeight + item.clientHeight;
      }
    }
  } else {
    // noImage
    if (totalHeight + 90 < 1050) {
      groupList_1.value[groupList_1.value.length - 1].noImage = true;
      totalHeight += 90;
    } else {
      groupList_1.value.push({
        page: groupList_1.value[groupList_1.value.length - 1].page + 1,
        itemList: [],
        imageList: [],
        imageListTable: [],
        itemListTable: [],
        showImageTitle: false,
        noImage: true,
      });
      totalHeight = headerHeight + 90;
    }
  }

  // 判断是否有页尾统计第一行
  if (totalHeight + 49 < 1050) {
    groupList_1.value[groupList_1.value.length - 1].showSummary1 = true;
    totalHeight += 49;
  } else {
    groupList_1.value.push({
      page: groupList_1.value[groupList_1.value.length - 1].page + 1,
      itemList: [],
      imageList: [],
      imageListTable: [],
      itemListTable: [],
      showImageTitle: false,
      showSummary1: true,
    });
    totalHeight = headerHeight + 49;
  }

  // 判断是否有页尾统计第二行
  if (totalHeight + 49 < 1050) {
    groupList_1.value[groupList_1.value.length - 1].showSummary2 = true;
    totalHeight += 49;
  } else {
    groupList_1.value.push({
      page: groupList_1.value[groupList_1.value.length - 1].page + 1,
      itemList: [],
      imageList: [],
      imageListTable: [],
      itemListTable: [],
      showImageTitle: false,
      showSummary2: true,
    });
    totalHeight = headerHeight + 49;
  }

  // 判断是否有页尾统计第三行
  if (totalHeight + 49 < 1050) {
    groupList_1.value[groupList_1.value.length - 1].showSummary3 = true;
    totalHeight += 49;
  } else {
    groupList_1.value.push({
      page: groupList_1.value[groupList_1.value.length - 1].page + 1,
      itemList: [],
      imageList: [],
      imageListTable: [],
      itemListTable: [],
      showImageTitle: false,
      showSummary3: true,
    });
    totalHeight = headerHeight + 49;
  }

  groupList.value = filterTable(groupList_1.value);
}
</script>

<style lang="scss" scoped>
div,
table,
tr,
td,
th,
tbody,
thead,
span,
image {
  padding: 0;
  margin: 0;
}
.app-container {
  height: inherit;
  overflow: scroll;
  padding: 0;
}

:deep(.printDialog .el-dialog__body) {
  padding: 10px !important;
  height: calc(100vh - 220px);
  overflow: scroll;
}

// table {
//   page-break-inside: avoid;
// }

// table + table {
//   page-break-before: always;
// }

.dashed-border {
  width: 100%;
  border-collapse: collapse; /* 使边框合并为单一边框 */
  border: 1px solid #333;
}

.dashed-border td,
.dashed-border th {
  color: #333;
  font-size: 13px;
  border: 1px solid #333;
  min-height: 30px;
  padding: 4px 6px;
  overflow-wrap: anywhere;
  line-height: 20px;
  word-break: break-all;
}

.page-break {
  page-break-before: always;
}

tr {
  page-break-inside: avoid;
}

.bold td {
  font-weight: 600;
  text-align: center;
}

td {
  text-align: center;
}

.left td {
  text-align: left;
}

.box1 {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.box1 div:nth-child(1) {
  font-size: 14px;
}
.box1 div:nth-child(2) {
  line-height: 20px;
  font-size: 13px;
}
</style>
